<!--
 * @Description: 
-->
<!--
 * @Description: 
-->
<template>
  <div class="home">
    <input
      type="button"
      title="开启摄像头"
      value="开启摄像头"
      @click="getMedia"
    />
    <br />
    <video id="video" width="500px" height="500px" autoplay="autoplay"></video>
    <br />
    <canvas ref="canvasRef" id="canvas" width="500px" height="500px"></canvas>
    <br />
    <button id="snap" @click="takePhoto">拍照</button>
    <img src="" id="imgTag" alt="" />
  </div>
</template>
<script>
import { reactive, defineComponent, toRefs, onMounted, ref } from "vue";

export default defineComponent({
  components: {},
  setup() {
    const state = reactive({
      video: null,
      canvas: null,
    });

    const canvasRef = ref(null);
    onMounted(() => {
      //获得video摄像头区域
      state.canvas = document.getElementById("canvas");
    });

    function getMedia() {
      state.video = document.querySelector("video");
      navigator.mediaDevices
        .getUserMedia({
          audio: true,
          video: { width: 200, height: 150 },
        })
        .then(function (stream) {
          try {
            video.src = window.URL.createObjectURL(stream);
          } catch (e) {
            state.video.srcObject = stream;
            state.video.onloadedmetadata = function (e) {
              video.play();
            };
          }
        })
        .catch(function (err) {
          console.log(err); //如果无法调用摄像头，这里会提示错误
        });
    }

    // 拍照
    function takePhoto() {
      getMedia()
      //获得Canvas对象
      let video = document.getElementById("video");
      let canvas = document.getElementById("canvas");
      let ctx = canvas.getContext("2d");
      ctx.drawImage(video, 0, 0, 500, 500);
      let img = document.getElementById("canvas").toDataURL();
      alert(img);
      // 这里的img就是得到的图片
      document.getElementById("imgTag").src = img;
    }

    return {
      canvasRef,
      ...toRefs(state),
      takePhoto,
      getMedia,
    };
  },
});
</script>
<style lang="scss" scoped>
.home {
  font-size: 0.32rem;
}
</style>
